package com.example.s01helloworld.controller;

import com.example.s01helloworld.model.Admin;
import com.example.s01helloworld.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController
{
    // SpringMVC请求传参

    //    @RequestMapping("/getUser")
    @RequestMapping(value="/getUser",method = RequestMethod.GET)
    public User getUser()
    {
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setPass("123456");
        return user;
    }

    // 1. 绑定简单数据
    @RequestMapping(value="/getUser2",method = RequestMethod.GET)
    public User getUser2(String username,int age)
    {
        User user = new User();
        user.setName(username);
        user.setAge(age);
        user.setPass("123456");

        return user;
    }

    // 2. 绑定对象
    @RequestMapping(value="/getUser3",method = RequestMethod.GET)
    public User getUser3(User user)
    {
        return user;
    }

    // 3. 路径传参
    @RequestMapping(value="/getUser4/{name}",method = RequestMethod.GET)
    public User getUser4(@PathVariable String name)
    {
        User user = new User();
        user.setName(name);
        user.setAge(18);
        user.setPass("123456");
        return user;
    }


    // 参数校验功能

    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    public String saveUser(@Valid User user,BindingResult result)
    {
        System.out.println(user);
        if(result.hasErrors())
        {
            List<ObjectError> list = result.getAllErrors();
            for(ObjectError e:list)
            {
                System.out.println(e.getCode()+"-"+e.getDefaultMessage());
            }
        }
        return "ok";
    }


    @Autowired
    private Admin person;

    @RequestMapping("/testPerson")
    public Admin testPerson()
    {
        return person;
    }
}
